package com.aabte.nettyleran.netty.http.xml.httpencoder;

import com.aabte.nettyleran.netty.http.xml.HttpXmlResponse;
import com.aabte.nettyleran.netty.http.xml.entity.Order;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.util.List;

/**
 * @author Daniel
 * @version 1.0
 * @date 2020/3/14
 */
public class HttpXmlResponseEncoder extends AbstractHttpXmlEncoder<HttpXmlResponse> {
    @Override
    protected void encode(ChannelHandlerContext ctx, HttpXmlResponse msg, List<Object> out) throws Exception {
        ByteBuf body = encode0(ctx, (Order) msg.getResult());
        FullHttpResponse response = msg.getHttpResponse();
        if (null == response) {
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, body);
        } else {
            response = new DefaultFullHttpResponse(response.protocolVersion(), response.status(), body);
        }

        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/xml");
        HttpHeaderUtil.setContentLength(response, body.readableBytes());
        out.add(response);
    }
}
